home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 June / maximum-cd-2009-06.iso / DiscContents / gimp-2.6.5-i686-setup.exe / {app} / lib / gimp / 2.0 / python / gimpfu,2.py < prev    next >
Encoding:
Python Source  |  2009-02-15  |  25.5 KB  |  818 lines

  1. #   Gimp-Python - allows the writing of GIMP plug-ins in Python.
  2. #   Copyright (C) 1997  James Henstridge <james@daa.com.au>
  3. #
  4. #   This program is free software; you can redistribute it and/or modify
  5. #   it under the terms of the GNU General Public License as published by
  6. #   the Free Software Foundation; either version 2 of the License, or
  7. #   (at your option) any later version.
  8. #
  9. #   This program is distributed in the hope that it will be useful,
  10. #   but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. #   GNU General Public License for more details.
  13. #
  14. #   You should have received a copy of the GNU General Public License
  15. #   along with this program; if not, write to the Free Software
  16. #   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  17.  
  18. '''Simple interface to writing GIMP plug-ins in Python.
  19.  
  20. Instead of worrying about all the user interaction, saving last used values
  21. and everything, the gimpfu module can take care of it for you.  It provides
  22. a simple register() function that will register your plug-in if needed, and
  23. cause your plug-in function to be called when needed.
  24.  
  25. Gimpfu will also handle showing a user interface for editing plug-in parameters
  26. if the plug-in is called interactively, and will also save the last used
  27. parameters, so the RUN_WITH_LAST_VALUES run_type will work correctly.  It
  28. will also make sure that the displays are flushed on completion if the plug-in
  29. was run interactively.
  30.  
  31. When registering the plug-in, you do not need to worry about specifying
  32. the run_type parameter.
  33.  
  34. A typical gimpfu plug-in would look like this:
  35.   from gimpfu import *
  36.  
  37.   def plugin_func(image, drawable, args):
  38.               #do what plugins do best
  39.   register(
  40.               "plugin_func",
  41.               "blurb",
  42.               "help message",
  43.               "author",
  44.               "copyright",
  45.               "year",
  46.               "My plug-in",
  47.               "*",
  48.               [
  49.                   (PF_IMAGE, "image", "Input image"),
  50.                   (PF_DRAWABLE, "drawable", "Input drawable"),
  51.                   (PF_STRING, "arg", "The argument", "default-value")
  52.               ],
  53.               [],
  54.               plugin_func, menu="<Image>/Somewhere")
  55.   main()
  56.  
  57. The call to "from gimpfu import *" will import all the gimp constants into
  58. the plug-in namespace, and also import the symbols gimp, pdb, register and
  59. main.  This should be just about all any plug-in needs.
  60.  
  61. You can use any of the PF_* constants below as parameter types, and an
  62. appropriate user interface element will be displayed when the plug-in is
  63. run in interactive mode.  Note that the the PF_SPINNER and PF_SLIDER types
  64. expect a fifth element in their description tuple -- a 3-tuple of the form
  65. (lower,upper,step), which defines the limits for the slider or spinner.
  66.  
  67. If want to localize your plug-in, add an optional domain parameter to the
  68. register call. It can be the name of the translation domain or a tuple that
  69. consists of the translation domain and the directory where the translations
  70. are installed.
  71. '''
  72.  
  73. import string as _string
  74. import math
  75. import gimp
  76. import gimpcolor
  77. from gimpenums import *
  78. pdb = gimp.pdb
  79.  
  80. import gettext
  81. t = gettext.translation('gimp20-python', gimp.locale_directory, fallback=True)
  82. _ = t.ugettext
  83.  
  84. class error(RuntimeError): pass
  85. class CancelError(RuntimeError): pass
  86.  
  87. PF_INT8        = PDB_INT8
  88. PF_INT16       = PDB_INT16
  89. PF_INT32       = PDB_INT32
  90. PF_INT         = PF_INT32
  91. PF_FLOAT       = PDB_FLOAT
  92. PF_STRING      = PDB_STRING
  93. PF_VALUE       = PF_STRING
  94. #PF_INT8ARRAY   = PDB_INT8ARRAY
  95. #PF_INT16ARRAY  = PDB_INT16ARRAY
  96. #PF_INT32ARRAY  = PDB_INT32ARRAY
  97. #PF_INTARRAY    = PF_INT32ARRAY
  98. #PF_FLOATARRAY  = PDB_FLOATARRAY
  99. #PF_STRINGARRAY = PDB_STRINGARRAY
  100. PF_COLOR       = PDB_COLOR
  101. PF_COLOUR      = PF_COLOR
  102. PF_REGION      = PDB_REGION
  103. PF_DISPLAY     = PDB_DISPLAY
  104. PF_IMAGE       = PDB_IMAGE
  105. PF_LAYER       = PDB_LAYER
  106. PF_CHANNEL     = PDB_CHANNEL
  107. PF_DRAWABLE    = PDB_DRAWABLE
  108. PF_VECTORS     = PDB_VECTORS
  109. #PF_SELECTION   = PDB_SELECTION
  110. #PF_BOUNDARY    = PDB_BOUNDARY
  111. #PF_PATH        = PDB_PATH
  112. #PF_STATUS      = PDB_STATUS
  113.  
  114. PF_TOGGLE      = 1000
  115. PF_BOOL        = PF_TOGGLE
  116. PF_SLIDER      = 1001
  117. PF_SPINNER     = 1002
  118. PF_ADJUSTMENT  = PF_SPINNER
  119.  
  120. PF_FONT        = 1003
  121. PF_FILE        = 1004
  122. PF_BRUSH       = 1005
  123. PF_PATTERN     = 1006
  124. PF_GRADIENT    = 1007
  125. PF_RADIO       = 1008
  126. PF_TEXT        = 1009
  127. PF_PALETTE     = 1010
  128. PF_FILENAME    = 1011
  129. PF_DIRNAME     = 1012
  130. PF_OPTION      = 1013
  131.  
  132. _type_mapping = {
  133.     PF_INT8        : PDB_INT8,
  134.     PF_INT16       : PDB_INT16,
  135.     PF_INT32       : PDB_INT32,
  136.     PF_FLOAT       : PDB_FLOAT,
  137.     PF_STRING      : PDB_STRING,
  138.     #PF_INT8ARRAY   : PDB_INT8ARRAY,
  139.     #PF_INT16ARRAY  : PDB_INT16ARRAY,
  140.     #PF_INT32ARRAY  : PDB_INT32ARRAY,
  141.     #PF_FLOATARRAY  : PDB_FLOATARRAY,
  142.     #PF_STRINGARRAY : PDB_STRINGARRAY,
  143.     PF_COLOR       : PDB_COLOR,
  144.     PF_REGION      : PDB_REGION,
  145.     PF_DISPLAY     : PDB_DISPLAY,
  146.     PF_IMAGE       : PDB_IMAGE,
  147.     PF_LAYER       : PDB_LAYER,
  148.     PF_CHANNEL     : PDB_CHANNEL,
  149.     PF_DRAWABLE    : PDB_DRAWABLE,
  150.     PF_VECTORS     : PDB_VECTORS,
  151.  
  152.     PF_TOGGLE      : PDB_INT32,
  153.     PF_SLIDER      : PDB_FLOAT,
  154.     PF_SPINNER     : PDB_INT32,
  155.  
  156.     PF_FONT        : PDB_STRING,
  157.     PF_FILE        : PDB_STRING,
  158.     PF_BRUSH       : PDB_STRING,
  159.     PF_PATTERN     : PDB_STRING,
  160.     PF_GRADIENT    : PDB_STRING,
  161.     PF_RADIO       : PDB_STRING,
  162.     PF_TEXT        : PDB_STRING,
  163.     PF_PALETTE     : PDB_STRING,
  164.     PF_FILENAME    : PDB_STRING,
  165.     PF_DIRNAME     : PDB_STRING,
  166.     PF_OPTION      : PDB_INT32,
  167. }
  168.  
  169. _obj_mapping = {
  170.     PF_INT8        : int,
  171.     PF_INT16       : int,
  172.     PF_INT32       : int,
  173.     PF_FLOAT       : float,
  174.     PF_STRING      : str,
  175.     #PF_INT8ARRAY   : list,
  176.     #PF_INT16ARRAY  : list,
  177.     #PF_INT32ARRAY  : list,
  178.     #PF_FLOATARRAY  : list,
  179.     #PF_STRINGARRAY : list,
  180.     PF_COLOR       : gimpcolor.RGB,
  181.     PF_REGION      : int,
  182.     PF_DISPLAY     : gimp.Display,
  183.     PF_IMAGE       : gimp.Image,
  184.     PF_LAYER       : gimp.Layer,
  185.     PF_CHANNEL     : gimp.Channel,
  186.     PF_DRAWABLE    : gimp.Drawable,
  187.     PF_VECTORS     : gimp.Vectors,
  188.  
  189.     PF_TOGGLE      : bool,
  190.     PF_SLIDER      : float,
  191.     PF_SPINNER     : int,
  192.  
  193.     PF_FONT        : str,
  194.     PF_FILE        : str,
  195.     PF_BRUSH       : str,
  196.     PF_PATTERN     : str,
  197.     PF_GRADIENT    : str,
  198.     PF_RADIO       : str,
  199.     PF_TEXT        : str,
  200.     PF_PALETTE     : str,
  201.     PF_FILENAME    : str,
  202.     PF_DIRNAME     : str,
  203.     PF_OPTION      : int,
  204. }
  205.  
  206. _registered_plugins_ = {}
  207.  
  208. def register(proc_name, blurb, help, author, copyright, date, label,
  209.              imagetypes, params, results, function,
  210.              menu=None, domain=None, on_query=None, on_run=None):
  211.     '''This is called to register a new plug-in.'''
  212.  
  213.     # First perform some sanity checks on the data
  214.     def letterCheck(str):
  215.         allowed = _string.letters + _string.digits + '_' + '-'
  216.         for ch in str:
  217.             if not ch in allowed:
  218.         return 0
  219.         else:
  220.             return 1
  221.  
  222.     if not letterCheck(proc_name):
  223.         raise error, "procedure name contains illegal characters"
  224.  
  225.     for ent in params:
  226.         if len(ent) < 4:
  227.             raise error, ("parameter definition must contain at least 4 "
  228.                           "elements (%s given: %s)" % (len(ent), ent))
  229.  
  230.         if type(ent[0]) != int:
  231.             raise error, "parameter types must be integers"
  232.  
  233.         if not letterCheck(ent[1]):
  234.             raise error, "parameter name contains illegal characters"
  235.  
  236.     for ent in results:
  237.         if len(ent) < 3:
  238.             raise error, ("result definition must contain at least 3 elements "
  239.                           "(%s given: %s)" % (len(ent), ent))
  240.  
  241.         if type(ent[0]) != type(42):
  242.             raise error, "result types must be integers"
  243.  
  244.         if not letterCheck(ent[1]):
  245.             raise error, "result name contains illegal characters"
  246.  
  247.     plugin_type = PLUGIN
  248.  
  249.     if (not proc_name[:7] == 'python-' and
  250.         not proc_name[:7] == 'python_' and
  251.         not proc_name[:10] == 'extension-' and
  252.         not proc_name[:10] == 'extension_' and
  253.         not proc_name[:8] == 'plug-in-' and
  254.         not proc_name[:8] == 'plug_in_' and
  255.         not proc_name[:5] == 'file-' and
  256.         not proc_name[:5] == 'file_'):
  257.            proc_name = 'python-fu-' + proc_name
  258.  
  259.     # if menu is not given, derive it from label
  260.     need_compat_params = False
  261.     if menu is None and label:
  262.         fields = label.split('/')
  263.         if fields:
  264.             label = fields.pop()
  265.             menu = '/'.join(fields)
  266.             need_compat_params = True
  267.  
  268.         if need_compat_params and plugin_type == PLUGIN:
  269.             file_params = [(PDB_STRING, "filename", "The name of the file", ""),
  270.                            (PDB_STRING, "raw-filename", "The name of the file", "")]
  271.  
  272.             if menu is None:
  273.                 pass
  274.             elif menu[:6] == '<Load>':
  275.                 params[0:0] = file_params
  276.             elif menu[:7] == '<Image>' or menu[:6] == '<Save>':
  277.                 params.insert(0, (PDB_IMAGE, "image", "Input image", None))
  278.                 params.insert(1, (PDB_DRAWABLE, "drawable", "Input drawable", None))
  279.                 if menu[:6] == '<Save>':
  280.                     params[2:2] = file_params
  281.  
  282.     _registered_plugins_[proc_name] = (blurb, help, author, copyright,
  283.                                        date, label, imagetypes,
  284.                                        plugin_type, params, results,
  285.                                        function, menu, domain,
  286.                                        on_query, on_run)
  287.  
  288. def _query():
  289.     for plugin in _registered_plugins_.keys():
  290.         (blurb, help, author, copyright, date,
  291.          label, imagetypes, plugin_type,
  292.          params, results, function, menu, domain,
  293.          on_query, on_run) = _registered_plugins_[plugin]
  294.  
  295.         def make_params(params):
  296.             return [(_type_mapping[x[0]],
  297.                      x[1],
  298.                      _string.replace(x[2], "_", "")) for x in params]
  299.  
  300.         params = make_params(params)
  301.         # add the run mode argument ...
  302.         params.insert(0, (PDB_INT32, "run-mode",
  303.                                      "Interactive, Non-Interactive"))
  304.  
  305.         results = make_params(results)
  306.  
  307.         if domain:
  308.             try:
  309.                 (domain, locale_dir) = domain
  310.                 gimp.domain_register(domain, locale_dir)
  311.             except ValueError:
  312.                 gimp.domain_register(domain)
  313.  
  314.         gimp.install_procedure(plugin, blurb, help, author, copyright,
  315.                                date, label, imagetypes, plugin_type,
  316.                                params, results)
  317.  
  318.         if menu:
  319.             gimp.menu_register(plugin, menu)
  320.         if on_query:
  321.             on_query()
  322.  
  323. def _get_defaults(proc_name):
  324.     import gimpshelf
  325.     (blurb, help, author, copyright, date,
  326.      label, imagetypes, plugin_type,
  327.      params, results, function, menu, domain,
  328.      on_query, on_run) = _registered_plugins_[proc_name]
  329.  
  330.     key = "python-fu-save--" + proc_name
  331.  
  332.     if gimpshelf.shelf.has_key(key):
  333.         return gimpshelf.shelf[key]
  334.     else:
  335.         # return the default values
  336.         return [x[3] for x in params]
  337.  
  338. def _set_defaults(proc_name, defaults):
  339.     import gimpshelf
  340.  
  341.     key = "python-fu-save--" + proc_name
  342.     gimpshelf.shelf[key] = defaults
  343.  
  344. def _interact(proc_name, start_params):
  345.     (blurb, help, author, copyright, date,
  346.      label, imagetypes, plugin_type,
  347.      params, results, function, menu, domain,
  348.      on_query, on_run) = _registered_plugins_[proc_name]
  349.  
  350.     def run_script(run_params):
  351.         params = start_params + tuple(run_params)
  352.         _set_defaults(proc_name, params)
  353.         return apply(function, params)
  354.  
  355.     params = params[len(start_params):]
  356.  
  357.     # short circuit for no parameters ...
  358.     if len(params) == 0:
  359.          return run_script([])
  360.  
  361.     import pygtk
  362.     pygtk.require('2.0')
  363.  
  364.     import gimpui
  365.     import gtk
  366. #    import pango
  367.  
  368.     defaults = _get_defaults(proc_name)
  369.     defaults = defaults[len(start_params):]
  370.  
  371.     class EntryValueError(Exception):
  372.         pass
  373.  
  374.     def warning_dialog(parent, primary, secondary=None):
  375.         dlg = gtk.MessageDialog(parent, gtk.DIALOG_DESTROY_WITH_PARENT,
  376.                                         gtk.MESSAGE_WARNING, gtk.BUTTONS_CLOSE,
  377.                                         primary)
  378.         if secondary:
  379.             dlg.format_secondary_text(secondary)
  380.         dlg.run()
  381.         dlg.destroy()
  382.  
  383.     def error_dialog(parent, proc_name):
  384.         import sys, traceback
  385.  
  386.         exc_str = exc_only_str = _('Missing exception information')
  387.  
  388.         try:
  389.             etype, value, tb = sys.exc_info()
  390.             exc_str = ''.join(traceback.format_exception(etype, value, tb))
  391.             exc_only_str = ''.join(traceback.format_exception_only(etype, value))
  392.         finally:
  393.             etype = value = tb = None
  394.  
  395.         title = _("An error occured running %s") % proc_name
  396.         dlg = gtk.MessageDialog(parent, gtk.DIALOG_DESTROY_WITH_PARENT,
  397.                                         gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
  398.                                         title)
  399.         dlg.format_secondary_text(exc_only_str)
  400.  
  401.         alignment = gtk.Alignment(0.0, 0.0, 1.0, 1.0)
  402.         alignment.set_padding(0, 0, 12, 12)
  403.         dlg.vbox.pack_start(alignment)
  404.         alignment.show()
  405.  
  406.         expander = gtk.Expander(_("_More Information"));
  407.         expander.set_use_underline(True)
  408.         expander.set_spacing(6)
  409.         alignment.add(expander)
  410.         expander.show()
  411.  
  412.         scrolled = gtk.ScrolledWindow()
  413.         scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
  414.         scrolled.set_size_request(-1, 200)
  415.         expander.add(scrolled)
  416.         scrolled.show()
  417.  
  418.  
  419.         label = gtk.Label(exc_str)
  420.         label.set_alignment(0.0, 0.0)
  421.         label.set_padding(6, 6)
  422.         label.set_selectable(True)
  423.         scrolled.add_with_viewport(label)
  424.         label.show()
  425.  
  426.         def response(widget, id):
  427.             widget.destroy()
  428.  
  429.         dlg.connect("response", response)
  430.         dlg.set_resizable(True)
  431.         dlg.show()
  432.  
  433.     # define a mapping of param types to edit objects ...
  434.     class StringEntry(gtk.Entry):
  435.         def __init__(self, default=''):
  436.             gtk.Entry.__init__(self)
  437.             self.set_text(str(default))
  438.  
  439.         def get_value(self):
  440.             return self.get_text()
  441.  
  442.     class TextEntry(gtk.ScrolledWindow):
  443.         def __init__ (self, default=''):
  444.             gtk.ScrolledWindow.__init__(self)
  445.             self.set_shadow_type(gtk.SHADOW_IN)
  446.  
  447.             self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
  448.             self.set_size_request(100, -1)
  449.  
  450.             self.view = gtk.TextView()
  451.             self.add(self.view)
  452.             self.view.show()
  453.  
  454.             self.buffer = self.view.get_buffer()
  455.  
  456.             self.set_value(str(default))
  457.  
  458.         def set_value(self, text):
  459.             self.buffer.set_text(text)
  460.  
  461.         def get_value(self):
  462.             return self.buffer.get_text(self.buffer.get_start_iter(),
  463.                                         self.buffer.get_end_iter())
  464.  
  465.     class IntEntry(StringEntry):
  466.         def get_value(self):
  467.             try:
  468.                 return int(self.get_text())
  469.             except ValueError, e:
  470.                 raise EntryValueError, e.args
  471.  
  472.     class FloatEntry(StringEntry):
  473.             def get_value(self):
  474.                 try:
  475.                     return float(self.get_text())
  476.                 except ValueError, e:
  477.                     raise EntryValueError, e.args
  478.  
  479. #    class ArrayEntry(StringEntry):
  480. #            def get_value(self):
  481. #                return eval(self.get_text(), {}, {})
  482.  
  483.  
  484.     def precision(step):
  485.         # calculate a reasonable precision from a given step size
  486.         if math.fabs(step) >= 1.0 or step == 0.0:
  487.             digits = 0
  488.         else:
  489.             digits = abs(math.floor(math.log10(math.fabs(step))));
  490.         if digits > 20:
  491.             digits = 20
  492.         return int(digits)
  493.  
  494.     class SliderEntry(gtk.HScale):
  495.         # bounds is (upper, lower, step)
  496.         def __init__(self, default=0, bounds=(0, 100, 5)):
  497.             step = bounds[2]
  498.             self.adj = gtk.Adjustment(default, bounds[0], bounds[1],
  499.                                       step, 10 * step, 0)
  500.             gtk.HScale.__init__(self, self.adj)
  501.             self.set_digits(precision(step))
  502.  
  503.         def get_value(self):
  504.             return self.adj.value
  505.  
  506.     class SpinnerEntry(gtk.SpinButton):
  507.         # bounds is (upper, lower, step)
  508.         def __init__(self, default=0, bounds=(0, 100, 5)):
  509.             step = bounds[2]
  510.             self.adj = gtk.Adjustment(default, bounds[0], bounds[1],
  511.                                       step, 10 * step, 0)
  512.             gtk.SpinButton.__init__(self, self.adj, step, precision(step))
  513.  
  514.     class ToggleEntry(gtk.ToggleButton):
  515.         def __init__(self, default=0):
  516.             gtk.ToggleButton.__init__(self)
  517.  
  518.             self.label = gtk.Label(_("No"))
  519.             self.add(self.label)
  520.             self.label.show()
  521.  
  522.             self.connect("toggled", self.changed)
  523.  
  524.             self.set_active(default)
  525.  
  526.         def changed(self, tog):
  527.             if tog.get_active():
  528.                 self.label.set_text(_("Yes"))
  529.             else:
  530.                 self.label.set_text(_("No"))
  531.  
  532.         def get_value(self):
  533.             return self.get_active()
  534.  
  535.     class RadioEntry(gtk.VBox):
  536.         def __init__(self, default=0, items=((_("Yes"), 1), (_("No"), 0))):
  537.             gtk.VBox.__init__(self, homogeneous=False, spacing=2)
  538.  
  539.             button = None
  540.  
  541.             for (label, value) in items:
  542.                 button = gtk.RadioButton(button, label)
  543.                 self.pack_start(button)
  544.                 button.show()
  545.  
  546.                 button.connect("toggled", self.changed, value)
  547.  
  548.                 if value == default:
  549.                     button.set_active(True)
  550.                     self.active_value = value
  551.  
  552.         def changed(self, radio, value):
  553.             if radio.get_active():
  554.                 self.active_value = value
  555.  
  556.         def get_value(self):
  557.             return self.active_value
  558.  
  559.     class ComboEntry(gtk.ComboBox):
  560.         def __init__(self, default=0, items=()):
  561.             store = gtk.ListStore(str)
  562.             for item in items:
  563.                 store.append([item])
  564.  
  565.             gtk.ComboBox.__init__(self, model=store)
  566.  
  567.             cell = gtk.CellRendererText()
  568.             self.pack_start(cell)
  569.             self.set_attributes(cell, text=0)
  570.  
  571.             self.set_active(default)
  572.  
  573.         def get_value(self):
  574.             return self.get_active()
  575.  
  576.     def FileSelector(default=''):
  577.        if default and default.endswith('/'):
  578.            selector = DirnameSelector
  579.            if default == '/': default = ''
  580.        else:
  581.            selector = FilenameSelector
  582.        return selector(default)
  583.  
  584.     class FilenameSelector(gtk.FileChooserButton):
  585.         def __init__(self, default='', save_mode=False):
  586.             gtk.FileChooserButton.__init__(self,
  587.                                            _("Python-Fu File Selection"))
  588.             self.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
  589.             if default:
  590.                 self.set_filename(default)
  591.  
  592.         def get_value(self):
  593.             return self.get_filename()
  594.  
  595.     class DirnameSelector(gtk.FileChooserButton):
  596.         def __init__(self, default=''):
  597.             gtk.FileChooserButton.__init__(self,
  598.                                            _("Python-Fu Folder Selection"))
  599.             self.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
  600.             if default:
  601.                 self.set_filename(default)
  602.  
  603.         def get_value(self):
  604.             return self.get_filename()
  605.  
  606.     _edit_mapping = {
  607.             PF_INT8        : IntEntry,
  608.             PF_INT16       : IntEntry,
  609.             PF_INT32       : IntEntry,
  610.             PF_FLOAT       : FloatEntry,
  611.             PF_STRING      : StringEntry,
  612.             #PF_INT8ARRAY   : ArrayEntry,
  613.             #PF_INT16ARRAY  : ArrayEntry,
  614.             #PF_INT32ARRAY  : ArrayEntry,
  615.             #PF_FLOATARRAY  : ArrayEntry,
  616.             #PF_STRINGARRAY : ArrayEntry,
  617.             PF_COLOR       : gimpui.ColorSelector,
  618.             PF_REGION      : IntEntry,  # should handle differently ...
  619.             PF_IMAGE       : gimpui.ImageSelector,
  620.             PF_LAYER       : gimpui.LayerSelector,
  621.             PF_CHANNEL     : gimpui.ChannelSelector,
  622.             PF_DRAWABLE    : gimpui.DrawableSelector,
  623.             PF_VECTORS     : gimpui.VectorsSelector,
  624.  
  625.             PF_TOGGLE      : ToggleEntry,
  626.             PF_SLIDER      : SliderEntry,
  627.             PF_SPINNER     : SpinnerEntry,
  628.             PF_RADIO       : RadioEntry,
  629.             PF_OPTION      : ComboEntry,
  630.  
  631.             PF_FONT        : gimpui.FontSelector,
  632.             PF_FILE        : FileSelector,
  633.             PF_FILENAME    : FilenameSelector,
  634.             PF_DIRNAME     : DirnameSelector,
  635.             PF_BRUSH       : gimpui.BrushSelector,
  636.             PF_PATTERN     : gimpui.PatternSelector,
  637.             PF_GRADIENT    : gimpui.GradientSelector,
  638.             PF_PALETTE     : gimpui.PaletteSelector,
  639.             PF_TEXT        : TextEntry
  640.     }
  641.  
  642.     if on_run:
  643.         on_run()
  644.  
  645.     tooltips = gtk.Tooltips()
  646.  
  647.     dialog = gimpui.Dialog(proc_name, 'python-fu', None, 0, None, proc_name,
  648.                            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
  649.                             gtk.STOCK_OK, gtk.RESPONSE_OK))
  650.  
  651.     dialog.set_alternative_button_order((gtk.RESPONSE_OK, gtk.RESPONSE_CANCEL))
  652.  
  653.     dialog.set_transient()
  654.  
  655.     vbox = gtk.VBox(False, 12)
  656.     vbox.set_border_width(12)
  657.     dialog.vbox.pack_start(vbox)
  658.     vbox.show()
  659.  
  660.     if blurb:
  661.         if domain:
  662.             try:
  663.                 (domain, locale_dir) = domain
  664.                 trans = gettext.translation(domain, locale_dir, fallback=True)
  665.             except ValueError:
  666.                 trans = gettext.translation(domain, fallback=True)
  667.             blurb = trans.ugettext(blurb)
  668.         box = gimpui.HintBox(blurb)
  669.         vbox.pack_start(box, expand=False)
  670.         box.show()
  671.  
  672.     table = gtk.Table(len(params), 2, False)
  673.     table.set_row_spacings(6)
  674.     table.set_col_spacings(6)
  675.     vbox.pack_start(table, expand=False)
  676.     table.show()
  677.  
  678.     def response(dlg, id):
  679.         if id == gtk.RESPONSE_OK:
  680.             dlg.set_response_sensitive(gtk.RESPONSE_OK, False)
  681.             dlg.set_response_sensitive(gtk.RESPONSE_CANCEL, False)
  682.  
  683.             params = []
  684.  
  685.             try:
  686.                 for wid in edit_wids:
  687.                     params.append(wid.get_value())
  688.             except EntryValueError:
  689.                 warning_dialog(dialog, _("Invalid input for '%s'") % wid.desc)
  690.             else:
  691.                 try:
  692.                     dialog.res = run_script(params)
  693.                 except Exception:
  694.                     dlg.set_response_sensitive(gtk.RESPONSE_CANCEL, True)
  695.                     error_dialog(dialog, proc_name)
  696.                     raise
  697.  
  698.         gtk.main_quit()
  699.  
  700.     dialog.connect("response", response)
  701.  
  702.     edit_wids = []
  703.     for i in range(len(params)):
  704.         pf_type = params[i][0]
  705.         name = params[i][1]
  706.         desc = params[i][2]
  707.         def_val = defaults[i]
  708.  
  709.         label = gtk.Label(desc)
  710.         label.set_use_underline(True)
  711.         label.set_alignment(0.0, 0.5)
  712.         table.attach(label, 1, 2, i, i+1, xoptions=gtk.FILL)
  713.         label.show()
  714.  
  715.         if pf_type in (PF_SPINNER, PF_SLIDER, PF_RADIO, PF_OPTION):
  716.             wid = _edit_mapping[pf_type](def_val, params[i][4])
  717.         else:
  718.             wid = _edit_mapping[pf_type](def_val)
  719.  
  720.         label.set_mnemonic_widget(wid)
  721.  
  722.         table.attach(wid, 2,3, i,i+1, yoptions=0)
  723.  
  724.         if pf_type != PF_TEXT:
  725.             tooltips.set_tip(wid, desc, None)
  726.         else:
  727.             #Attach tip to TextView, not to ScrolledWindow
  728.             tooltips.set_tip(wid.view, desc, None)
  729.         wid.show()
  730.  
  731.         wid.desc = desc
  732.         edit_wids.append(wid)
  733.  
  734.     progress_vbox = gtk.VBox(False, 6)
  735.     vbox.pack_end(progress_vbox, expand=False)
  736.     progress_vbox.show()
  737.  
  738.     progress = gimpui.ProgressBar()
  739.     progress_vbox.pack_start(progress)
  740.     progress.show()
  741.  
  742. #    progress_label = gtk.Label()
  743. #    progress_label.set_alignment(0.0, 0.5)
  744. #    progress_label.set_ellipsize(pango.ELLIPSIZE_MIDDLE)
  745.  
  746. #    attrs = pango.AttrList()
  747. #    attrs.insert(pango.AttrStyle(pango.STYLE_ITALIC, 0, -1))
  748. #    progress_label.set_attributes(attrs)
  749.  
  750. #    progress_vbox.pack_start(progress_label)
  751. #    progress_label.show()
  752.  
  753.     tooltips.enable()
  754.     dialog.show()
  755.  
  756.     gtk.main()
  757.  
  758.     if hasattr(dialog, 'res'):
  759.         res = dialog.res
  760.         dialog.destroy()
  761.         return res
  762.     else:
  763.         dialog.destroy()
  764.         raise CancelError
  765.  
  766. def _run(proc_name, params):
  767.     run_mode = params[0]
  768.     func = _registered_plugins_[proc_name][10]
  769.  
  770.     if run_mode == RUN_NONINTERACTIVE:
  771.         return apply(func, params[1:])
  772.  
  773.     script_params = _registered_plugins_[proc_name][8]
  774.  
  775.     min_args = 0
  776.     if len(params) > 1:
  777.         for i in range(1, len(params)):
  778.             param_type = _obj_mapping[script_params[i - 1][0]]
  779.             if not isinstance(params[i], param_type):
  780.                 break
  781.  
  782.         min_args = i
  783.  
  784.     if len(script_params) > min_args:
  785.         start_params = params[:min_args + 1]
  786.  
  787.         if run_mode == RUN_WITH_LAST_VALS:
  788.             default_params = _get_defaults(proc_name)
  789.             params = start_params + default_params[min_args:]
  790.         else:
  791.             params = start_params
  792.     else:
  793.        run_mode = RUN_NONINTERACTIVE
  794.  
  795.     if run_mode == RUN_INTERACTIVE:
  796.         try:
  797.             res = _interact(proc_name, params[1:])
  798.         except CancelError:
  799.             return
  800.     else:
  801.         res = apply(func, params[1:])
  802.  
  803.     gimp.displays_flush()
  804.  
  805.     return res
  806.  
  807. def main():
  808.     '''This should be called after registering the plug-in.'''
  809.     gimp.main(None, None, _query, _run)
  810.  
  811. def fail(msg):
  812.     '''Display and error message and quit'''
  813.     gimp.message(msg)
  814.     raise error, msg
  815.  
  816. def N_(message):
  817.     return message
  818.